// import { connected } from "process";
import {
  Post,
  Get
} from "../../utils/request.js"

Page({
  //detail.js
  data: {
    deviceId: '',
    macId: '',
    bluetoothMac: '', //机器id
    serviceList: [ //支持多款设备多个主服务
      { //1.0设备
        needUseService: [{
          serviceUUID: '00001000-0000-1000-8000-00805F9B34FB',
          writeCharacteristicsId: '00001001-0000-1000-8000-00805F9B34FB',
          notifyCharacteristicsId: '00001002-0000-1000-8000-00805F9B34FB'
        }]
      }, { //2.0设备
        needUseService: [{
            serviceUUID: '0000FFC0-0000-1000-8000-00805F9B34FB',
            writeCharacteristicsId: '0000FFC1-0000-1000-8000-00805F9B34FB',
            notifyCharacteristicsId: '0000FFC2-0000-1000-8000-00805F9B34FB'
          },
          {
            serviceUUID: '0000FFF0-0000-1000-8000-00805F9B34FB',
            writeCharacteristicsId: '0000FFF2-0000-1000-8000-00805F9B34FB',
            notifyCharacteristicsId: '',
            readCharacteristicsId: '0000FFF3-0000-1000-8000-00805F9B34FB'
          },
          {
            serviceUUID: '0000FFD0-0000-1000-8000-00805F9B34FB',
            writeCharacteristicsId: '',
            notifyCharacteristicsId: '',
            readCharacteristicsId: '0000FFD3-0000-1000-8000-00805F9B34FB'
          }
        ]
      }, { //3.0设备
        needUseService: [{
          serviceUUID: '00010203-0405-0607-0809-0A0B0C0D1910',
          writeCharacteristicsId: '00010203-0405-0607-0809-0A0B0C0D2B11',
          notifyCharacteristicsId: '00010203-0405-0607-0809-0A0B0C0D2B10'
        }]
      }
    ],
    maxSearchTime: 15, // 最大搜索时间
  },
  //获取二维码中的蓝牙name，然后连接
  onLoad: function (options) {
    wx.showLoading({
      title: '请打开蓝牙',
    });
    console.log(options);
    this.setData({
      deviceName: options.id,
    });
    console.log('设备的Name', this.data.deviceName);
    var that = this;
    var canshu = "/cabinet/code/" + options.id
    Get(canshu, {})
      .then(res => {
        this.setData({
          bluetoothMac: res.data.bluetoothMac
        })

        console.log(res, " 到时候也会放在二维码里面的 ")
        console.log(res.data.cabinetBrandDTO.parameter, "res.data.cabinetBrandDTO.parameter")
        var jsonObj = res.data.cabinetBrandDTO.parameter
        console.log(jsonObj, "jsonObj")
        var keyValue = "";
        // 处理好的json字符串
        var jsonStr = "";
        for (var key in jsonObj) {
          keyValue += key + ':"' + jsonObj[key] + '",';
        }
        console.log( keyValue,"keyValue")
        // 去除最后一个逗号
        keyValue = keyValue.substring(0, keyValue.length - 1);
        jsonStr = "{" + keyValue + "}";
        console.log(jsonStr);
      })

    var deviceName = options.id;
    wx.closeBluetoothAdapter({
      success: function (res) {
        console.log('关闭蓝牙模块');
        /* 初始化蓝牙适配器 */
        wx.openBluetoothAdapter({
          success: function (res) {
            console.log('初始化蓝牙适配器成功');
            wx.hideLoading();
            wx.showLoading({
              title: '请稍后....',
            });
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success: function (res) {
                console.log('这里是开始搜索附近设备', res);
                //添加延迟
                setTimeout(() => {
                  wx.getBluetoothDevices({
                    success: function (res) {
                      console.log(res, "搜索的设备")
                      //在搜索到的所有蓝牙中找到需要连接的那一个蓝牙
                      for (var i = 0; i < res.devices.length; i++) {
                        if (res.devices[i].name == 'B5588' || res.devices[i].deviceId == that.data.bluetoothMac) {
                          console.log(res.devices[i], "匹配合适的数据打印")
                          that.setData({
                            deviceId: res.devices[i].deviceId,
                          })
                          /* 连接中动画 */
                          wx.showLoading({
                            title: '正在连接...',
                          });
                          that.CreateBLEConnection();
                          // return
                        }
                      }
                    },
                    fail: function () {
                      console.log("搜索蓝牙设备失败")
                    }
                  });
                }, 1300);
              },
            });
          },
        })
      }
    });
  },
  //连接蓝牙
  CreateBLEConnection: function () {
    var that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log('停止搜索设备', res)
      }
    })
    /* 开始连接蓝牙设备 */
    console.log(that.data.deviceId, "链接蓝牙参数")
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log("链接成功", res)
        wx.getBLEDeviceServices({
          deviceId: that.data.deviceId,
          success: function (service) {
            console.log("连接成功返回的数据", service)
            var all_UUID = service.services; //取出所有的服务

            var UUID_lenght = all_UUID.length; //获取到服务数组的长度
            /* 遍历服务数组 */
            for (var index = 0; index < UUID_lenght; index++) {
              var ergodic_UUID = all_UUID[index].uuid; //取出服务里面的UUID
              if (ergodic_UUID == '00010203-0405-0607-0809-0A0B0C0D1910') {
                that.setData({
                  serviceId: ergodic_UUID //确定需要的服务UUID
                });
                //  return
              }
            };
            // wx.showLoading()
            that.Characteristics(); //调用获取特征值函数
          },
          fail: (res) => {
            console.log(res, "all_UUID[index].uuid")
          },
        });
      },
      fail: (res) => {
        console.log(res, "连接成功的下一步失败")
      },
    })
  },
  Characteristics: function () {
    var that = this;
    var device_characteristics = [];
    var characteristics_uuid = {};

    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function (res) {
        console.log("调用特征值调用参数", res)

        var characteristics = res.characteristics; //获取到所有特征值
        var characteristics_length = characteristics.length; //获取到特征值数组的长度

        /* 遍历获取characteristicsId */
        console.log(characteristics, "获取特征值")
        for (var index = 0; index < characteristics_length; index++) {
          var characteristics_UUID = characteristics[index].uuid; //取出特征值里面的UUID
          if (characteristics_UUID == "00010203-0405-0607-0809-0A0B0C0D2B11") {
            that.setData({
              characteristicsId: characteristics_UUID //确定的写入UUID
            });
          };
        };
        that.SendTap(); //发送指令
      },
    })
  },
  /* 发送指令 */
  SendTap: function () {
    var that = this;
    var value_ascii = "";
    var value_initial = "&voltage"; //发送的信息
    /* 以Ascii字符发送 */
    var value_split = value_initial.split(''); //将字符一个一个分开
    for (var i = 0; i < value_split.length; i++) {
      value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); //转为Ascii字符后连接起
    }
    var value = value_ascii;
    var write_function = that.write(value); //调用数据发送函数
  },
  write: function (str) {
    var that = this;
    var value = str;

    /* 将数值转为ArrayBuffer类型数据 */
    var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }));
    var buffer = typedArray.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicsId,
      value: buffer,
      success: function (res) {
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {

        /* 调用失败时，再次调用 */
        //  登录先
        wx.writeBLECharacteristicValue({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.characteristicsId,
          value: buffer,
          success: function (res) {
            console.log('第2次数据发送成功', res);
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (res) {
            console.log('第2次调用失败', res);
            /* 调用失败时，再次调用 */
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: that.data.characteristicsId,
              value: buffer,
              success: function (res) {
                console.log('第3次数据发送成功', res);
                wx.showToast({
                  title: '发送成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function (res) {
                console.log('第3次调用失败', res);
              }
            });
          }
        });
      }
    });
  },
  // 开柜
  tapName() {
    this.maxbyte = 20
    let promiseResolve = null;
    let that = this
    // let str = '&voltage'
    let str = '<B452b989|5|0000028>'
    // let str ='<C452b989|3|1>'
    let val = '';
    for (let i = 0; i < str.length; i++) {
      val += str.charCodeAt(i).toString(16);
    }

    //写入命令  data.order:蓝牙指令   data.index:写入特征值所属服务于serviceList的下标，不写默认0
    return new Promise((resolve, reject) => {
      if (val) {
        let buffer = new ArrayBuffer(val.length / 2);
        let dataView = new DataView(buffer);

        for (var i = 0; i < val.length / 2; i++) {
          dataView.setUint8(i, '0x' + val.substr(i * 2, 2));

        }
        let pos = 0;
        let bytes = buffer.byteLength;
        // 26766f6c74616765
        while (bytes > 0) {
          let tmpBuffer;

          if (bytes > that.maxbyte) {
            tmpBuffer = buffer.slice(pos, pos + that.maxbyte);
            pos += that.maxbyte;
            bytes -= that.maxbyte;

          } else {
            tmpBuffer = buffer.slice(pos, pos + bytes);

            pos += bytes;
            bytes -= bytes;
          }

          promiseResolve = resolve;


          wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicsId,
            value: tmpBuffer,
            success: res => {

              if (this.serviceIndex == 1) { //2.0设备没有硬件答复，默认成功
                if (promiseResolve) {
                  promiseResolve({
                    code: 1,
                    status: 1
                  });
                }
                promiseResolve = null;
              }
            },
            fail: err => {

              this.onPublish('bleError', {
                code: err.errCode || -1,
                msg: err.errCode ? this.tips[err.errCode] : err.errMsg
              });
            }
          })
        }

      }
    });















  },


  //

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;



    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log('断开设备连接', res);
      }
    });
  },


})